package com.dbsop.operation.index;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;

@Slf4j
public class TcIndexOperation implements IndexOperation {

    private TransportClient tc = null;

    public TcIndexOperation(TransportClient tc) {
        this.tc = tc;
    }

    @Override
    public boolean existsIndex(String index) {
        return tc.admin().indices().prepareExists(index)
                .execute().actionGet().isExists();
    }


    @Override
    public void checkCreateIndex(IndexParams indexParams) {
        if (!existsIndex(indexParams.getIndexName())) {
            log.info("索引不存在: " + indexParams.getIndexName());
            createIndex(indexParams);
        }
    }

    @Override
    public void createIndex(IndexParams indexParams) {
        String indexName = indexParams.getIndexName();
        String alias = indexParams.getAlias();
        Integer maxResult = indexParams.getMaxResult();
        Integer replicas = indexParams.getReplicas();
        Integer shared = indexParams.getShared();
        CreateIndexRequestBuilder createIndexRequestBuilder = tc.admin().indices().prepareCreate(indexName);
        Settings.Builder builder = Settings.builder();
        Settings settings = null;
        if (shared != null && shared >0 ){
            builder.put("number_of_shards", shared);
        }
        if (replicas != null && replicas >0){
            builder.put("number_of_replicas", replicas);
        }
        if (maxResult!=null && maxResult >0){
            builder.put("max_result_window", maxResult);
        }
        if (alias!=null && !alias.trim().equals("")){
            createIndexRequestBuilder.addAlias(new Alias(alias));
        }
        settings = builder.build();
        createIndexRequestBuilder.setSettings(settings);
        boolean acknowledged = createIndexRequestBuilder.execute().actionGet().isAcknowledged();
        if (acknowledged) log.info("索引创建成功: " + indexName+"; 分片为:" +shared +"; 副本数量为:" + replicas);
        else log.info("索引创建失败: " + indexName);
    }

}
